package com.atguigu.serviceedu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.serviceedu.entity.EduSubject;
import com.atguigu.serviceedu.entity.excel.SubjectExcel;
import com.atguigu.serviceedu.entity.subject.OneSubject;
import com.atguigu.serviceedu.entity.subject.TwoSubject;
import com.atguigu.serviceedu.listener.SubjectExcelListener;
import com.atguigu.serviceedu.mapper.EduSubjectMapper;
import com.atguigu.serviceedu.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-08-29
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void readExccel(MultipartFile file, EduSubjectService subjectService) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectExcel.class,new SubjectExcelListener(subjectService)).sheet().doRead();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllSubject() {
        List<OneSubject> oneSubjects=new ArrayList<>();
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("parent_id","0");
        List<EduSubject> firstSubjects = baseMapper.selectList(wrapper);

        QueryWrapper<EduSubject> wrapper1=new QueryWrapper<>();
        wrapper1.ne("parent_id","0");
        List<EduSubject> secondSubjects=baseMapper.selectList(wrapper1);

        for(int i=0;i<firstSubjects.size();i++){
            EduSubject eduSubject= firstSubjects.get(i);
            OneSubject oneSubject=new OneSubject();
            BeanUtils.copyProperties(eduSubject,oneSubject);
            oneSubjects.add(oneSubject);
            for(int j=0;j<secondSubjects.size();j++){
                EduSubject second=secondSubjects.get(j);
                if(eduSubject.getId().equals(second.getParentId())){
                    TwoSubject twoSubject=new TwoSubject();
                    BeanUtils.copyProperties(second,twoSubject);
                    oneSubjects.get(i).getChildren().add(twoSubject);
                }
            }
        }

        return oneSubjects;
    }
}
